package com.recipedb.recipedb.repository;

import com.recipedb.recipedb.entity.Favorite;
import com.recipedb.recipedb.entity.FavoriteId;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface FavoriteRepository extends JpaRepository<Favorite, FavoriteId> {

    List<Favorite> findByUserIdOrderByCreatedAtDesc(Long userId);

    boolean existsByUserIdAndRecipeId(Long userId, Long recipeId);

    @Modifying
    @Query("DELETE FROM Favorite f WHERE f.userId = :userId AND f.recipeId = :recipeId")
    int deleteByUserIdAndRecipeId(@Param("userId") Long userId, @Param("recipeId") Long recipeId);

    @Query("SELECT f.recipeId FROM Favorite f WHERE f.userId = :userId")
    List<Long> findRecipeIdsByUserId(@Param("userId") Long userId);

    @Query("SELECT COUNT(f) FROM Favorite f WHERE f.recipeId = :recipeId")
    Long countByRecipeId(@Param("recipeId") Long recipeId);

    @Query("SELECT COUNT(f) FROM Favorite f WHERE f.recipeId IN " +
            "(SELECT r.id FROM Recipe r WHERE r.userId = :userId)")
    Long countTotalFavoritesByUserId(@Param("userId") Long userId);

    @Query("SELECT f.recipeId, COUNT(f) FROM Favorite f WHERE f.recipeId IN :recipeIds GROUP BY f.recipeId")
    List<Object[]> countByRecipeIds(@Param("recipeIds") List<Long> recipeIds);
}